package com.example.acdemo.utils;

import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashMap;
import java.util.Map;
import java.util.Calendar;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.Iterator;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class WatchStatsManager {
    private static final String TAG = "WatchStatsManager";
    private static final String PREFS_NAME = "watch_stats";
    private static final String KEY_STATS = "stats";
    private static final String KEY_DATE = "date";
    
    private static WatchStatsManager instance;
    private final SharedPreferences prefs;
    private final Map<String, WatchData> watchDataMap = new HashMap<>();
    private OnStatsResetListener resetCallback;
    
    public static class WatchData {
        public final String name;
        public final int degree;
        public final int level;
        
        public WatchData(String name, int degree, int level) {
            this.name = name;
            this.degree = degree;
            this.level = level;
        }
        
        @Override
        public String toString() {
            return String.format("%s [Lv.%d] (%d/360)", name, level, degree);
        }
    }
    
    private WatchStatsManager(Context context) {
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        loadData();
    }
    
    public static synchronized WatchStatsManager getInstance(Context context) {
        if (instance == null) {
            instance = new WatchStatsManager(context.getApplicationContext());
        }
        return instance;
    }
    
    public void updateWatchDegree(String uperId, String name, int degree, int level) {
        watchDataMap.put(uperId, new WatchData(name, degree, level));
        saveData();
        // Logger.d(TAG, String.format("更新数据: %s [Lv.%d] (%d/360)", name, level, degree));
    }
    
    public Map<String, WatchData> getAllStats() {
        return new HashMap<>(watchDataMap);
    }
    
    public String getNickname(String uperId) {
        WatchData data = watchDataMap.get(uperId);
        return data != null ? data.name : uperId;
    }
    
    private void saveData() {
        try {
            JSONObject stats = new JSONObject();
            for (Map.Entry<String, WatchData> entry : watchDataMap.entrySet()) {
                JSONObject data = new JSONObject();
                data.put("name", entry.getValue().name);
                data.put("degree", entry.getValue().degree);
                data.put("level", entry.getValue().level);
                stats.put(entry.getKey(), data);
            }
            
            prefs.edit()
                .putString(KEY_STATS, stats.toString())
                .apply();
        } catch (JSONException e) {
            Logger.e(TAG, "保存数据失败", e);
        }
    }
    
    public boolean loadData() {
        String savedDate = prefs.getString(KEY_DATE, "");
        String today = getCurrentDate();
        
        if (!today.equals(savedDate)) {
            watchDataMap.clear();
            prefs.edit()
                .putString(KEY_DATE, today)
                .putString(KEY_STATS, "{}")
                .apply();
            
            if (resetCallback != null) {
                resetCallback.onStatsReset();
            }
            Logger.i(TAG, "数据已重置 (新的一天)");
            return true;
        }
        
        try {
            String statsJson = prefs.getString(KEY_STATS, "{}");
            JSONObject stats = new JSONObject(statsJson);
            watchDataMap.clear();
            
            Iterator<String> keys = stats.keys();
            while (keys.hasNext()) {
                String uperId = keys.next();
                JSONObject data = stats.getJSONObject(uperId);
                String name = data.getString("name");
                int degree = data.getInt("degree");
                int level = data.optInt("level", 1);
                watchDataMap.put(uperId, new WatchData(name, degree, level));
            }
            return false;
        } catch (JSONException e) {
            Logger.e(TAG, "加载数据失败", e);
            return false;
        }
    }
    
    private String getCurrentDate() {
        return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            .format(new Date());
    }
    
    public interface OnStatsResetListener {
        void onStatsReset();
    }
    
    public void setOnStatsResetListener(OnStatsResetListener listener) {
        this.resetCallback = listener;
    }
} 